<template>
    <div class="book-list">
        <div class="header-container">
            <div class="user-info">
                <span>欢迎您，{{ userCode }}</span>
                <el-button type="danger" size="small" @click="handleLogout">退出登录</el-button>
            </div>
        </div>

        <el-card class="main-content">
            <div slot="header">
                <span>图书列表</span>
                <el-input v-model="searchForm.bookName" placeholder="请输入图书名称" style="width: 200px; margin-left: 20px"
                    @keyup.enter.native="handleSearch"></el-input>
                <el-select v-model="searchForm.bookType" placeholder="图书类型" style="width: 150px; margin-left: 10px">
                    <el-option label="全部" :value="null"></el-option>
                    <el-option v-for="item in bookTypes" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
                <el-select v-model="searchForm.isBorrowed" placeholder="借阅状态" style="width: 150px; margin-left: 10px">
                    <el-option label="全部" :value="null"></el-option>
                    <el-option label="已借阅" :value="1"></el-option>
                    <el-option label="未借阅" :value="0"></el-option>
                </el-select>
                <el-button type="primary" style="margin-left: 10px" @click="loadBooks">搜索</el-button>
            </div>

            <el-table :data="bookList" border style="width: 100%">
                <el-table-column prop="bookCode" label="图书编号" width="120"></el-table-column>
                <el-table-column prop="bookName" label="图书名称" width="200"></el-table-column>
                <el-table-column prop="bookType" label="图书分类" width="100">
                    <template slot-scope="scope">
                        {{ getBookTypeName(scope.row.bookType) }}
                    </template>
                </el-table-column>
                <el-table-column prop="bookAuthor" label="作者" width="120"></el-table-column>
                <el-table-column prop="publishPress" label="出版社"></el-table-column>
                <el-table-column prop="count" label="借阅次数" width="120"></el-table-column>
                <el-table-column label="操作" width="120" align="center">
                    <template slot-scope="scope">
                        <el-button v-if="scope.row.isBorrowed === 0" type="text"
                            @click="handleBorrow(scope.row)">申请借阅</el-button>
                        <span v-else>已借阅</span>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNo"
                :page-sizes="[10, 20, 50]" :page-size="pageSize" layout="total, sizes, prev, pager, next" :total="total"
                style="margin-top: 20px; text-align: right"></el-pagination>
        </el-card>
    </div>
</template>

<script>
export default {
    name: 'BookList',
    data() {
        return {
            userCode: localStorage.getItem('userCode'),
            bookList: [],
            bookTypes: [],
            pageNo: 1,
            pageSize: 10,
            total: 0,
            searchForm: {
                bookName: '',
                bookType: null,
                isBorrowed: null
            }
        }
    },
    created() {
        this.loadBookTypes()  // 添加加载图书类型
        this.loadBooks()
    },
    methods: {
        async loadBookTypes() {
            try {
                const response = await this.$axios({
                    method: 'get',
                    url: '/api/book/types',
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('token')
                    }
                })
                if (response.data.code === 0) {
                    this.bookTypes = response.data.data || []  // 添加默认空数组
                    if (this.bookTypes.length === 0) {
                        this.$message.warning('获取图书类型列表为空')
                    }
                }
            } catch (error) {
                console.error('加载图书类型失败:', error)
                this.$message.error('加载图书类型失败')
            }
        },
        async loadBooks() {
            try {
                const response = await this.$axios({
                    method: 'get',
                    url: '/api/book/list',
                    params: {
                        pageNo: this.pageNo,
                        pageSize: this.pageSize,
                        bookName: this.searchForm.bookName,
                        bookType: this.searchForm.bookType,
                        isBorrowed: this.searchForm.isBorrowed
                    },
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('token')
                    }
                })

                if (response.data.code === 0) {
                    this.bookList = response.data.data.records
                    this.total = response.data.data.total
                }
            } catch (error) {
                console.error('加载图书列表失败:', error)
                this.$message.error('加载图书列表失败')
            }
        },

        handleSearch() {
            this.pageNo = 1
            this.loadBooks()
        },

        handleSizeChange(val) {
            this.pageSize = val
            this.loadBooks()
        },

        handleCurrentChange(val) {
            this.pageNo = val
            this.loadBooks()
        },

        getBookTypeName(type) {
            const found = this.bookTypes.find(item => item.value === type)
            return found ? found.label : '未知'
        },

        async handleBorrow(book) {
            try {
                const response = await this.$axios({
                    method: 'post',
                    url: '/api/book/borrow',
                    data: { bookId: book.bookId },
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('token')
                    }
                })
                
                if (response.data.code === 0) {
                    this.$message.success('借阅申请成功')
                    this.loadBooks()
                } else {
                    this.$message.error(response.data.msg || '借阅申请失败')
                }
            } catch (error) {
                console.error('借阅申请失败:', error)
                this.$message.error('借阅申请失败')
            }
        },

        async handleLogout() {
            try {
                await this.$axios({
                    method: 'post',
                    url: '/api/logout',
                    headers: {
                        'Authorization': 'Bearer ' + localStorage.getItem('token')
                    }
                })
                localStorage.removeItem('token')
                localStorage.removeItem('userCode')
                this.$router.push('/login')
                this.$message.success('退出登录成功')
            } catch (error) {
                console.error('退出登录失败:', error)
                this.$message.error('退出登录失败')
            }
        }
    }
}
</script>

<style scoped>
.book-list {
    padding: 20px;
    position: relative;
}

.header-container {
    position: fixed;
    top: 0;
    right: 0;
    left: 0;
    height: 50px;
    background-color: #fff;
    box-shadow: 0 1px 4px rgba(0, 0, 0, .1);
    z-index: 999;
}

.user-info {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    padding: 0 20px;
    height: 100%;
}

.user-info span {
    margin-right: 15px;
    font-size: 14px;
    color: #606266;
}

.main-content {
    margin-top: 70px;
    min-height: calc(100vh - 140px);
}
</style>